﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.IO;
using System.Reflection;

namespace MinistryStandardPlatformWeb.Controllers
{
    public class CommonController : Controller
    {
        //
        // GET: /Common/
        public ActionResult TableToExcel(FormCollection form)
        {
            try
            {
                string filename = form["title"]+".xls";
                string content = HttpUtility.HtmlDecode(form["content"]);
                content = content.Replace("<td", "<td style='vnd.ms-excel.numberformat:@;'");
                byte[] b = Encoding.GetEncoding("GB2312").GetBytes(content);//字串转byte阵列
                return File(b, @"application/ms-excel", Server.UrlPathEncode(filename));//输出档案给Client端
            }
            catch (System.Exception ex)
            {
                Response.Write("<script>alert('数据已过期，请重新查询')</scirpt>");
                return Json(new { success = "false", message = ex.Message });
            }    
        }


        /// <summary>
        /// Excle导出数据
        /// </summary>
        /// <typeparam name="T">类对象</typeparam>
        /// <param name="list">对象数据</param>
        /// <param name="column">类字段，字段对应列名</param>
        /// <param name="filename">excel表名</param>
        public ActionResult ListToExcel<T>(List<T> list, Dictionary<string, string> column, string filename,HttpServerUtilityBase server)
        {
            if (list == null || list.Count == 0 || column == null || column.Count == 0)
            {
                return null;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            //-------------------------------表头读取开始------------------------------------------------

            try
            {
                sb.Append("<tr>");
                foreach (KeyValuePair<string, string> kvp in column)
                {

                    sb.Append("<th>" + kvp.Value + "</th>");

                }

                sb.Append("</tr>");
                //-------------------------------表头读取结束--------------------------------------------------------

                //--------------------------------数据读取start----------------------------------------------------------------------------------

                Type objType = typeof(T);

                BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;//反射标识 

                PropertyInfo[] propInfoArr = objType.GetProperties(bf); //获取映射列表

                foreach (T model in list)
                {
                    sb.Append("<tr>");

                    foreach (string key in column.Keys)
                    {

                        foreach (PropertyInfo propInfo in propInfoArr)
                        {

                            if (key == propInfo.Name)//判断头相对应的字段 
                            {

                                PropertyInfo modelProperty = model.GetType().GetProperty(propInfo.Name);

                                if (modelProperty != null)
                                {

                                    object objResult = modelProperty.GetValue(model, null);//获取值                        

                                    sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + ((objResult == null) ? string.Empty : objResult) + "</td>");

                                }

                            }

                        }



                    }

                    sb.Append("</tr>");

                }
                sb.Append("</table>");
                //------------------------------------------end----------------------------------------------------------------------------------

                byte[] b = Encoding.GetEncoding("GB2312").GetBytes((sb.ToString()));
                return File(b, @"application/ms-excel", server.UrlPathEncode(filename + ".xls"));//输出档案给Client端
            }
            catch (System.Exception ex)
            {
                ViewBag.Message = "导出出错";
                return View("ActionResult");
            }  
        }

    }
}
